import React, { useCallback, useEffect, useState } from 'react'
import { Button, Space, Table, Modal, Form, Input, message, Popconfirm, Checkbox } from 'antd';
import type { TableColumnsType } from 'antd';
import api from '../api/axios'
import type { PopconfirmProps } from 'antd';
// modal框
interface DataType {
    key: React.Key;
    name: string;
    age: number;
    address: string;
    description: string;
}

//form表单
type FieldType = {
    title?: string;
    content?: string;
    remember?: string;
};

function List() {
    const [list, setList] = useState<any>([])
    const [total, setTotal] = useState<number>(1)
    const [page, setPage] = useState<number>(1)
    const [pageSize, setPageSize] = useState<number>(10)
    const [title, setTitle] = useState<string>('')
    const [tit, setTit] = useState<string>('')
    const [editId, setEditID] = useState<string>('')
    //form表单
    const [form] = Form.useForm()

    const getData = async (title: string[]) => {
        const res = await api.get('/article/list', {
            params: {
                page,//页码  必传
                pageSize,//每页显示条数 必传
                keyword: title,//搜索标题
            }
        })
        console.log(res)
        setList(res.data.rows)
        setTotal(res.data.count)
    }
    //modal
    const [isModalOpen, setIsModalOpen] = useState<boolean>(false);
    const showModal = () => {
        setIsModalOpen(true);
        form.resetFields()
        setTit(true)
    };
    const edit = (record) => {
        setIsModalOpen(true)
        form.setFieldsValue(record)
        setEditID(record.id)
        setTit(false)
    }
    const handleOk = () => {
        setIsModalOpen(false);
    };

    const handleCancel = () => {
        setIsModalOpen(false);
    };
    //表单提交
    const onFinish: FormProps<FieldType>['onFinish'] = async (values) => {
        console.log('Success:', values);
        if (tit) {
            const res = await api.post('/article', {
                ...values,
                authorId: 47529555
            })
            console.log(res)
            getData()
            setIsModalOpen(false)
        } else {
            const res = await api.put(`/article/${editId}`, values)
            console.log(res)
            getData()
            setIsModalOpen(false)
        }
    };

    const onFinishFailed: FormProps<FieldType>['onFinishFailed'] = (errorInfo) => {
        console.log('Failed:', errorInfo);
    };
    //删除
    const confirm: PopconfirmProps['onConfirm'] = useCallback((id) => {
        message.success('Click on Yes');
        const sc = list.filter((item) => item.id !== id)
        setList(sc)
    }, [list]);

    const cancel: PopconfirmProps['onCancel'] = (e) => {
        console.log(e);
        message.error('Click on No');
    };
    //搜索
    const onFinish1: FormProps<FieldType>['onFinish'] = (values) => {
        console.log('Success:', values);
        const { title, content } = values
        getData(title, content)
    };

    const onFinishFailed1: FormProps<FieldType>['onFinishFailed'] = (errorInfo) => {
        console.log('Failed:', errorInfo);
    };
    //分页
    const chanlpage = (page, pageSize) => {
        setPage(page)
        setPageSize(pageSize)
    }
    //复选框
    const onChange1: CheckboxProps['onChange'] = (e) => {
        console.log(`checked = ${e.target.checked}`);
    };

    useEffect(() => {
        getData()
    }, [page, pageSize])
    const columns: TableColumnsType<DataType> = [
        {
            title: '用户ID',
            dataIndex: 'id',
            key: 'id',
            render: () => {
                return <Checkbox></Checkbox>
            }
        },
        {
            title: '用户昵称',
            dataIndex: 'title',
            key: 'title'
        },
        {
            title: 'content',
            dataIndex: 'content',
            key: 'content'
        },
        {
            title: '创建时间',
            dataIndex: 'createdAt',
            key: 'createdAt',
            filters: [
                {
                    text: '用户编号',
                    value: '用户编号',
                },
                {
                    text: '用户名称',
                    value: '用户名称',
                },
                {
                    text: '用户昵称',
                    value: '用户昵称',
                },
                {
                    text: '部门',
                    value: '部门',
                },
                {
                    text: '手机号码',
                    value: '手机号码',
                },
                {
                    text: '状态',
                    value: '状态',
                },
                {
                    text: '创建时间',
                    value: '创建时间',
                },
            ],
        },
        {
            title: '操作',
            key: 'action',
            render: (_, record) => (
                <Space size="middle">
                    <Popconfirm
                        title="消息提示"
                        description="您确定要删除吗?"
                        onConfirm={() => confirm(record.id)}
                        onCancel={cancel}
                        okText="是的"
                        cancelText="取消"
                    >
                        <Button danger>删除</Button>
                    </Popconfirm>
                    <a><Button onClick={() => edit(record)}>修改</Button></a>
                    <a><Button>查看</Button></a>
                </Space>
            ),
        },
    ];
    return (
        <div>
            <Button type="primary" onClick={showModal}>
                新增
            </Button>
            <Button type="primary" style={{ marginLeft: '30px' }}>展开/折叠</Button>
            <Form
                layout='inline'
                name="basic"
                labelCol={{ span: 8 }}
                wrapperCol={{ span: 16 }}
                style={{ maxWidth: 1200 }}
                initialValues={{ remember: true }}
                onFinish={onFinish1}
                onFinishFailed={onFinishFailed1}
                autoComplete="off"
            >
                <Form.Item<FieldType>
                    label="菜单名称"
                    name="title"
                >
                    <Input />
                </Form.Item>

                <Form.Item<FieldType>
                    label="状态"
                    name="content"
                >
                    <Input />
                </Form.Item>
                <Form.Item<FieldType>
                    label="手机号码"
                    name="content"
                >
                    <Input />
                </Form.Item>
                <Form.Item label={null}>
                    <Button type="primary" htmlType="submit">
                        搜索
                    </Button>
                </Form.Item>
            </Form>
            <div>
                <Table<DataType>
                    columns={columns}
                    rowKey='id'
                    expandable={{
                        expandedRowRender: (record) => <p style={{ margin: 0 }}>{record.description}</p>,
                        rowExpandable: (record) => record.name !== 'Not Expandable',
                    }}
                    dataSource={list}
                    pagination={{
                        total: total,
                        showSizeChanger: true,
                        showQuickJumper: true,
                        onChange: chanlpage,
                        showTotal: (total) => `Total ${total} items`
                    }}
                />
            </div>
            <div>
                <Modal
                    title={tit ? '新增用户' : '修改'}
                    closable={{ 'aria-label': 'Custom Close Button' }}
                    open={isModalOpen}
                    onOk={handleOk}
                    onCancel={handleCancel}
                >
                    <Form
                        form={form}
                        name="basic"
                        labelCol={{ span: 8 }}
                        wrapperCol={{ span: 16 }}
                        style={{ maxWidth: 600 }}
                        initialValues={{ remember: true }}
                        onFinish={onFinish}
                        onFinishFailed={onFinishFailed}
                        autoComplete="off"
                    >
                        <Form.Item<FieldType>
                            label="title"
                            name="title"
                            rules={[{ required: true, message: 'Please input your username!' }]}
                        >
                            <Input />
                        </Form.Item>

                        <Form.Item<FieldType>
                            label="content"
                            name="content"
                            rules={[{ required: true, message: 'Please input your password!' }]}
                        >
                            <Input />
                        </Form.Item>
                        <Form.Item label={null}>
                            <Button type="primary" htmlType="submit">
                                提交
                            </Button>
                        </Form.Item>
                    </Form>
                </Modal>
            </div>
        </div>
    )
}
export default List
